/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.easemob.helpdeskdemo.ui;

import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;

import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.helpdeskdemo.Constant;
import com.easemob.helpdeskdemo.DemoHelper;
import com.example.huanxinservice.R;

public class MainActivity extends BaseActivity implements EMEventListener {

	private MyConnectionListener connectionListener = null;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.em_activity_main);
		init();
	}

	@SuppressLint("NewApi")
	private void init() {

		// 注册一个监听连接状态的listener
		connectionListener = new MyConnectionListener();
		EMChatManager.getInstance().addConnectionListener(connectionListener);

		// 内部测试方法，请忽略
		registerInternalDebugReceiver();
	}

	public class MyConnectionListener implements EMConnectionListener {

		@Override
		public void onConnected() {

		}

		@Override
		public void onDisconnected(final int error) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (error == EMError.USER_REMOVED) {
						// 账号被移除
						DemoHelper.getInstance().logout(true, null);
						if (ChatActivity.activityInstance != null) {
							ChatActivity.activityInstance.finish();
						}
					} else if (error == EMError.CONNECTION_CONFLICT) {
						// 账号在其他地方登录
						DemoHelper.getInstance().logout(true, null);
						if (ChatActivity.activityInstance != null) {
							ChatActivity.activityInstance.finish();
						}
					} else {
						// 连接不到服务器

					}

				}
			});
		}

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// super.onSaveInstanceState(outState);
	}

	public void show(View view) {
		Intent intent = new Intent();
		intent.setClass(MainActivity.this, LoginActivity.class);
		intent.putExtra(Constant.MESSAGE_TO_INTENT_EXTRA,
				Constant.MESSAGE_TO_DEFAULT);
		startActivity(intent);
	}

	@Override
	protected void onResume() {
		super.onResume();
		DemoHelper.getInstance().pushActivity(this);
		// register the event listener when enter the foreground
		EMChatManager.getInstance().registerEventListener(
				this,
				new EMNotifierEvent.Event[] {
						EMNotifierEvent.Event.EventNewMessage,
						EMNotifierEvent.Event.EventOfflineMessage });
	}

	@Override
	protected void onStop() {
		super.onStop();
		// 把此activity 从foreground activity 列表里移除
		DemoHelper.getInstance().popActivity(this);
		EMChatManager.getInstance().unregisterEventListener(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (connectionListener != null) {
			EMChatManager.getInstance().removeConnectionListener(
					connectionListener);
		}
		try {
			unregisterReceiver(internalDebugReceiver);
		} catch (Exception e) {
		}
	}

	@Override
	public void onEvent(EMNotifierEvent event) {
		switch (event.getEvent()) {
		case EventNewMessage:
			EMMessage message = (EMMessage) event.getData();
			// 提示新消息
			DemoHelper.getInstance().getNotifier().onNewMsg(message);
			break;
		case EventOfflineMessage:
			// 处理离线消息
			List<EMMessage> messages = (List<EMMessage>) event.getData();
			// 消息提醒或只刷新UI
			DemoHelper.getInstance().getNotifier().onNewMesg(messages);
			break;
		default:
			break;
		}

	}

	private BroadcastReceiver internalDebugReceiver;

	/**
	 * 内部测试代码，开发者请忽略
	 */
	private void registerInternalDebugReceiver() {
		internalDebugReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				DemoHelper.getInstance().logout(true, null);
				if (ChatActivity.activityInstance != null) {
					ChatActivity.activityInstance.finish();
				}
			}
		};
		IntentFilter filter = new IntentFilter(getPackageName()
				+ ".em_internal_debug");
		registerReceiver(internalDebugReceiver, filter);
	}

}
